package com.only4play.portal.cp.message.jsonmessage;

import com.only4play.portal.common.session.InternalSession;
import com.only4play.portal.common.session.InternalSessionManager;
import com.only4play.portal.cp.api.CpService;
import com.only4play.portal.cp.bean.message.AbstractCpMessage;
import com.only4play.portal.cp.bean.message.jsonmessage.CpJsonMessage;
import com.only4play.portal.cp.bean.message.jsonmessage.CpJsonOutMessage;
import com.only4play.portal.cp.message.CpMessageRouter;
import com.only4play.portal.cp.message.CpMessageRouterRule;
import org.apache.commons.lang3.StringUtils;

public class JsonCpMessageRouter extends CpMessageRouter<CpJsonOutMessage, CpJsonMessage> {


    public JsonCpMessageRouter(CpService cpService) {
        super(cpService);
    }

    @Override
    public CpMessageRouterRule<CpJsonOutMessage, CpJsonMessage> rule() {
        return new JsonCpMessageRouterRule(this);
    }

    @Override
    protected void sessionEndAccess(CpJsonMessage jsonMessage) {
        InternalSession session = ((InternalSessionManager) this.sessionManager).findSession(jsonMessage.getFromUserName());
        if (session != null) {
            session.endAccess();
        }
    }

    @Override
    protected boolean isMsgDuplicated(CpJsonMessage jsonMessage) {
        StringBuilder messageId = new StringBuilder();
        if (jsonMessage.getMsgId() == null) {
            messageId.append(jsonMessage.getCreateAt())
                .append("-").append(StringUtils.trimToEmpty(String.valueOf(jsonMessage.getAgentId())))
                .append("-").append(jsonMessage.getFromUserName());
        } else {
            messageId.append(jsonMessage.getMsgId())
                .append("-").append(jsonMessage.getCreateAt())
                .append("-").append(jsonMessage.getFromUserName());
        }

        return this.messageDuplicateChecker.isDuplicate(messageId.toString());
    }
}
